package pl.poznan.put.cs.idss.students.kingcart.ui;

import java.awt.Canvas;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.util.logging.Logger;

import pl.poznan.put.cs.idss.students.kingcart.properties.Properties;

public class MainCanvas extends DoubleBuffer implements MouseMotionListener,
		MouseListener {

	private static final long serialVersionUID = -802113887678218545L;
	Logger log = Logger.getLogger("pl.poznan.put.cs.idss.students.kingcart");

	int width;
	int height;

	private GeneralWindow parent;
	private Image image = createImage(width, height);
	private AreaSelection areaSelection;

	private boolean isSelectionPossible = false;

	
	public MainCanvas(GeneralWindow parent) {
		this.parent = parent;
		
		width = Properties.number("canvas_width");
		height = Properties.number("canvas_height");

		areaSelection = new AreaSelection(this);

		addMouseListener(this);
		addMouseMotionListener(this);

		setSize(width, height);
		setVisible(true);

	}

	public void drawImage(Image cam) {
		if (cam == null) {
			log.severe("Image does not exist or is invalid");
			return;
		} else {
			image = cam;
		}
		if (isValid()) {
			update(getGraphics());
		} else {
			log.severe("Canvas is not valid - cannot draw");
		}
	}

	public void paintBuffer(Graphics g) {
		g.drawImage(image, 0, 0, width, height, this);
		if (areaSelection.getSelection() != null) {
			Graphics2D g2d = (Graphics2D) g;
			g2d.setColor(Color.YELLOW);
			g2d.draw(areaSelection.getSelection());
		}
	}

	public void drawNextFrame(Image cam) {
		image = cam;
		repaint();
	}

	public void mousePressed(MouseEvent e) {
		if (isSelectionPossible)
			areaSelection.initSelection(e.getPoint());
	}

	public void mouseReleased(MouseEvent e) {
		// TODO: track selection
		if (isSelectionPossible) {
			//areaSelection.getSubImage(image);
			parent.resume();
			areaSelection.unselect();
			isSelectionPossible = false;
		}
	}

	public void mouseDragged(MouseEvent e) {
		if (isSelectionPossible)
			areaSelection.select(e.getPoint());

	}

	public void mouseClicked(MouseEvent arg0) {
	}

	public void mouseEntered(MouseEvent arg0) {
	}

	public void mouseExited(MouseEvent arg0) {
	}

	public void mouseMoved(MouseEvent arg0) {
	}

	public void isSelectionPossible(boolean b) {
		this.isSelectionPossible = b;

	}
	public Rectangle getSelectedArea() {
	return areaSelection.getSelection();
	}

	public Image getImage() {
		return image;
		
	}

}
